import 'package:fish_redux/fish_redux.dart';
import 'dart:convert' as convert;
import 'action.dart';
import 'state.dart';
import '../../OrderView/model/order_view_model.dart';
import '../../../app_files.dart';

Reducer<PatrolOrderResultViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<PatrolOrderResultViewState>>{
      PatrolOrderResultViewAction.action: _onAction,
      PatrolOrderResultViewAction.onTapStatus: _onTapStatus,
      PatrolOrderResultViewAction.setOrderPhoto: _setOrderPhoto,
      PatrolOrderResultViewAction.setFixPhoto: _setFixPhoto,
      PatrolOrderResultViewAction.onGetData: _onGetData,
    },
  );
}

PatrolOrderResultViewState _onAction(PatrolOrderResultViewState state, Action action) {
  final PatrolOrderResultViewState newState = state.clone();
  return newState;
}


PatrolOrderResultViewState _onTapStatus(PatrolOrderResultViewState state, Action action) {
  final PatrolOrderResultViewState newState = state.clone()
    ..orderStatus = action.payload + 1;
  return newState;
}

PatrolOrderResultViewState _setOrderPhoto(PatrolOrderResultViewState state, Action action) {
  final PatrolOrderResultViewState newState = state.clone();
  newState.orderPhoto.add(action.payload);
  return newState;
}

PatrolOrderResultViewState _setFixPhoto(PatrolOrderResultViewState state, Action action) {
  final PatrolOrderResultViewState newState = state.clone();
  newState.repairPhotos.add(action.payload);
  return newState;
}

PatrolOrderResultViewState _onGetData(PatrolOrderResultViewState state, Action action) {
  final PatrolOrderResultViewState newState = state.clone();
  newState.orderStatus = int.tryParse(CommonUtils.checkNullToString(action.payload['ptworkResultstatus'])) ?? 0;
  newState.orderSignPhoto = action.payload['ptworkSignature'];
  String photos = action.payload['ptworkAttachment'] ?? '';
  newState.orderPhoto = photos.split(',');
  List list = convert.jsonDecode(CommonUtils.checkNullToString(action.payload['ptworkContent']));
  List<OrderConfigModel> items =
  list.map<OrderConfigModel>((e) => OrderConfigModel.fromJson(e)).toList();
  newState.items = items;
  newState.workerName =
      CommonUtils.checkNullToString(action.payload['ptworkInspectorname']);
  if (newState.orderStatus == 2) {
    String jsonContent = CommonUtils.checkNullToString(action.payload['ptworkArepairremark']);
    String fixPhotos = CommonUtils.checkNullToString(action.payload['ptworkArepairAfterAttachment']);
    print(jsonContent);
    Map info = convert.jsonDecode(jsonContent);
    newState.selfFixContentController.text =  info['RepairContent'];
    newState.repairPhotos = fixPhotos.split(',');
  }
  return newState;
}
